package com.itedge.solutionmanager.service.domain.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Service;

import com.itedge.infrastructure.service.domain.impl.AbstractJpaProcessEntityService;
import com.itedge.solutionmanager.domain.impl.Solution;
import com.itedge.solutionmanager.service.domain.ISolutionService;

/**
 * Service class for operations on Solution business object
 * @author jhe
 *
 */
@Service
public class SolutionService extends AbstractJpaProcessEntityService<Solution>
	implements ISolutionService {
	
	@PersistenceContext
    transient EntityManager entityManager;

	@Override
	protected EntityManager getEntityManager() {
		return this.entityManager;
	}

	@Override
	protected Class<Solution> getClassReference() {
		return Solution.class;
	}
	
	//TODO: rewrite to use CriteriaQuery
	@Override
	public List<Solution> findEntitiesByCriteria(Solution searchSolution, Integer maxResults) {
		/*CriteriaBuilder queryBuilder =this.entityManager.getCriteriaBuilder();
		CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
		CriteriaQuery<Object> qdef = queryBuilder.createQuery();
		Root solution = qdef.from(Solution.class);
		CriteriaQuery<Object> select = qdef.select(solution);
		// like on name
		Expression<String> literal = criteriaBuilder.upper(criteriaBuilder.literal((String) searchSolution.getName()));
		Predicate predicate = criteriaBuilder.like(criteriaBuilder.upper(solution.get("name")), literal);
		
		qdef.where(predicate);
		
		TypedQuery typedQuery = entityManager.createQuery(select);*/
		List<Solution> result  = null;
		try {
			TypedQuery<Solution> query = this.entityManager.createQuery("select o from Solution o " +
				"where upper(o.name) like upper(:searchName) or upper(o.initialInfo) like upper(:searchInitInfo)", 
					Solution.class);
			query.setParameter("searchName", '%'+searchSolution.getName()+'%');
			query.setParameter("searchInitInfo", '%'+searchSolution.getInitialInfo()+'%');
			if (maxResults != null) {
				query.setMaxResults(maxResults);
			}
			result = query.getResultList();
		} catch(EmptyResultDataAccessException e){
        	return null;
        } catch(NoResultException e) {
	        return null;
	    }
		return result;
	}
	
}